import qs from "qs";
import { successAlert } from "@/utils/message";

const BASE_URL = "http://127.0.0.1:7001/api/blog";

/***
 * @param {Object}  options 参数
 * @param {String} options.url URL地址
 * @param {Object} options.method 请求地址,默认get
 * @param {Object} options.data body内的参数
 * @param {Object} options.params 放到url后面的queryString
 * @param {Object} options.headers 要添加的头信息
 */
function request({
  url,
  method = "get",
  data = {},
  params = {},
  headers = { a: 1 }
}) {
  method = method.toLocaleUpperCase();
  let l = Object.keys(params).length,
    str = "";
  if (l > 0) {
    str = "?" + qs(params);
  }
  return new Promise((resolve, reject) => {
    $.ajax({
      url: BASE_URL + url + str,
      type: method,
      dataType: "json",
      processData: false,
      data,
      contentType: "application/json",
      headers,
      success(data) {
        // console.log("---------------ajax-Success-------------------", data);
        if (data.code == 0) {
          resolve(data);
        } else {
          successAlert(data.msg, "danger");
          reject(data);
        }
      },
      error(jqXHR, textStatus, errorThrown) {
        // 错误信息处理
        console.error(
          "-------------ajaxERROR-------------",
          jqXHR,
          textStatus,
          errorThrown
        );
        reject();
      }
    });
  });
}

export default request;
